import 'package:flutter/material.dart';
import 'package:gold/base/config.dart';
import 'package:gold/base/list_view_model.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/model/coupon_model.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';

/// Descriptions: 选择优惠券弹窗
/// [picked] 已选择优惠券
/// User: tangzhentao
/// Date: 4:58 下午 2021/12/7
///
Future<CouponPick?> showPickupCouponDialog({CouponPick? picked, required double minAmount}) async {
  return await showModalBottomSheet<CouponPick>(
      context: XfgNav.currentContext,
      isScrollControlled: true,
      isDismissible: false,
      builder: (_) => _PickupCouponWidget(picked: picked, minAmount: minAmount,)
  );
}

class _PickupCouponWidget extends StatelessWidget {
  /// 优惠券门槛金额
  final double minAmount;

  late final _PickupCouponViewmodel _vM;

  _PickupCouponWidget({required this.minAmount, CouponPick? picked}) {
    _vM = _PickupCouponViewmodel(ApiOrder.couponList, minAmount, picked == null || picked.noCoupon ? null:picked.coupon);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      type: MaterialType.transparency,
      child: Container(
        height: XfgSize().screenHeight * 0.65,
        padding: EdgeInsets.only(bottom: XfgSize().bottomBarHeight),
        decoration: BoxDecoration(color: XfgColor.background, borderRadius: BorderRadius.vertical(top: Radius.circular(XfgSize().size10))),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: XfgSize().size10, vertical: XfgSize().size20),
              alignment: Alignment.topCenter,
              child: Row(
                children: [
                  SizedBox.square(dimension: XfgSize().size24),
                  Expanded(child: XfgText('优惠券', fontSize: XfgSize().text20, color: XfgColor.text1D, bold: FontWeight.bold, textAlign: TextAlign.center)),
                  GestureDetector(
                    onTap: _handlePop,
                    child: Icon(Icons.close, size: XfgSize().size24, color: XfgColor.text1),
                  )
                ],
              ),
            ),
            Expanded(
              child: ProviderWidget<_PickupCouponViewmodel>(
                onInit: (data) => data.firstLoad(),
                model: _vM,
                builder: (ctx, coupon) => SmartRefresher(
                  controller: coupon.controller,
                  enablePullDown: true,
                  enablePullUp: true,
                  onRefresh: coupon.refresh,
                  onLoading: coupon.loadMore,
                  child: ListView.builder(
                    itemCount: coupon.list.length,
                    itemBuilder: (_, index) {
                      final model = coupon.list[index];
                      final isSelect = coupon.pickupCoupon?.userCouponId == model.userCouponId;
                      return GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: () {
                          if (!isSelect) {
                            coupon.changePickup(index);
                          }
                        },
                        child: Container(
                          margin: EdgeInsets.only(top: index == 0 ? 0:XfgSize().size10),
                          padding: EdgeInsets.symmetric(horizontal: XfgSize().size10),
                          child: Row(
                            children: [
                              Image.asset(isSelect ? Res.imagesPayRadioS:Res.imagesPayRadio, width: XfgSize().size20, height: XfgSize().size20),
                              Expanded(
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(XfgSize().size6),
                                  child: Container(
                                    margin: EdgeInsets.only(left: XfgSize().size20),
                                    color: XfgColor.white,
                                    height: XfgSize().size72,
                                    child: Row(
                                      children: [
                                        Expanded(
                                          flex: 2,
                                          child: Container(
                                            color: XfgColor.pickupCouponLeft,
                                            child: Column(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              children: [
                                                XfgText('¥${model.discountAmount?.toStringAsFixed(2)?? '0.00'}', fontSize: XfgSize().text16, color: XfgColor.theme, bold: FontWeight.bold),
                                                SizedBox(height: XfgSize().size8),
                                                XfgText('满¥$minAmount可用', fontSize: XfgSize().text12, color: XfgColor.theme)
                                              ],
                                            ),
                                          ),
                                        ),
                                        Expanded(
                                          flex: 3,
                                          child: Padding(
                                            padding: EdgeInsets.only(left: XfgSize().size16),
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              children: [
                                                XfgText(model.couponName?? '未知优惠券', fontSize: XfgSize().text16, color: XfgColor.text1D, bold: FontWeight.bold),
                                                SizedBox(height: XfgSize().size8),
                                                XfgText('有效期至${model.expiredAt?? ''}', fontSize: XfgSize().text12, color: XfgColor.text3)
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    )
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
              ),
            ),
            SizedBox(height: XfgSize().size10),
            TextButton(
              onPressed: _handlePop,
              style: xfgButtonStyle(Size(XfgSize().size170, XfgSize().size50), radius: XfgSize().size50),
              child: XfgText('选择', fontSize: XfgSize().text16, color: XfgColor.white),
            ),
          ],
        ),
      ),
    );
  }

  /// 处理返回
  void _handlePop() {
    if (_vM.pickupCoupon != null) {
      XfgNav.pop(CouponPick(false, _vM.pickupCoupon!));
    } else {
      if (_vM.state == PageState.empty) {
        XfgNav.pop(CouponPick(true, CouponModel()));
      } else {
        XfgNav.pop();
      }
    }
  }
}

/// 优惠券列表状态
class _PickupCouponViewmodel extends ListViewModel<CouponModel> {
  /// 选中优惠券
  CouponModel? pickupCoupon;
  /// 优惠券门槛金额
  final double minAmount;

  _PickupCouponViewmodel(super.api, this.minAmount, this.pickupCoupon) {
    setEmpty(msg: '暂无可用优惠券', rebuild: false);
  }

  /// 修改选中
  void changePickup(int index) {
    pickupCoupon = list[index];
    setSuccessChange();
  }

  @override
  Map<String, dynamic>? onOtherData() {
    return {'min_amount': minAmount};
  }
}

/// 优惠券选择结果
class CouponPick {
  /// 是否无可用优惠券
  final bool noCoupon;
  /// 优惠券
  final CouponModel coupon;

  CouponPick(this.noCoupon, this.coupon);
}